/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import model.DBManager;

/**
 *
 * @author sky
 */
public class SelectSongJFrame extends javax.swing.JFrame {

    /**
     * Creates new form SelectSongJFrame
     */
    public SelectSongJFrame() {
        em = DBManager.em;
        if (!(em.getTransaction().isActive())) {
            em.getTransaction().begin();
        }
        initComponents();
    }
    public SelectSongJFrame(EditListJFrame parent) {
        em = DBManager.em;
        this.parent = parent;
        if (!(em.getTransaction().isActive())) {
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        availableSongsQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT s FROM Song s");
        availableSongsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(availableSongsQuery.getResultList());
        timeRenderer1 = new controller.TimeRenderer();
        searchInput = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        searchJBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        cancelJBtn = new javax.swing.JButton();
        saveJBtn = new javax.swing.JButton();

        timeRenderer1.setText("timeRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("RadioStation");

        jLabel1.setText("Εισαγωγή Τραγουδιού");

        searchJBtn.setText("Αναζήτηση");
        searchJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchJBtnActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, availableSongsList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songDuration}"));
        columnBinding.setColumnName("Διάρκεια");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId.albumMusicGroupId.musicGroupName}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId.artistId.artistLname}"));
        columnBinding.setColumnName("Επίθ.Καλλιτέχνη");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId.artistId.artistFname}"));
        columnBinding.setColumnName("Όν.Καλλιτέχνη");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId.artistId.artistArtname}"));
        columnBinding.setColumnName("Ψευδ.Καλλιτέχνη");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(1).setCellRenderer(timeRenderer1);
        }

        cancelJBtn.setText("Ακύρωση");
        cancelJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelJBtnActionPerformed(evt);
            }
        });

        saveJBtn.setText("Επιλογή");
        saveJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveJBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(searchInput)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchJBtn))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 674, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(saveJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelJBtn)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchJBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 38, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveJBtn)
                    .addComponent(cancelJBtn))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchJBtnActionPerformed
        //pat3group sky:Αναζήτηση
        //Ψάχνω πρώτα τραγούδια καλλιτεχνών και τα καρφώνω στην availableSongsList
        //αφού πρώτα την αδειάσω
        availableSongsQuery = em.createQuery("SELECT s FROM Song s WHERE s.albumId.albumMusicGroupId IS NULL AND (UPPER(s.songTitle) LIKE :k OR UPPER(s.albumId.artistId.artistFname) LIKE :k OR UPPER(s.albumId.artistId.artistLname) LIKE :k OR UPPER(s.albumId.artistId.artistArtname) LIKE :k)").setParameter("k", "%" + searchInput.getText().toUpperCase() + "%");
        java.util.Collection data = availableSongsQuery.getResultList();
        for (Object entity : data) { em.refresh(entity); }
        availableSongsList.clear();
        availableSongsList.addAll(data);
        //προσθέτω στην ίδια λίστα και τραγούδια των συγκροτημάτων
        availableSongsQuery = em.createQuery("SELECT s FROM Song s WHERE s.albumId.artistId IS NULL AND (UPPER(s.songTitle) LIKE :k OR UPPER(s.albumId.albumMusicGroupId.musicGroupName) LIKE :k)").setParameter("k", "%" + searchInput.getText().toUpperCase() + "%");
        data = availableSongsQuery.getResultList();
        for (Object entity : data) { em.refresh(entity); }
        availableSongsList.addAll(data);
        if (searchInput.getText().trim().equals("")){
            availableSongsQuery = em.createQuery("SELECT s FROM Song s");
            data = availableSongsQuery.getResultList();
            for (Object entity : data) { em.refresh(entity); }
            availableSongsList.clear();
            availableSongsList.addAll(data);
        }
    }//GEN-LAST:event_searchJBtnActionPerformed

    private void cancelJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelJBtnActionPerformed
        submit(false); //do nothing and return to previus form
    }//GEN-LAST:event_cancelJBtnActionPerformed

    private void saveJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveJBtnActionPerformed
        // pat3group: sky - return selected song to previus form
        System.out.println("Select new song");
        int s = jTable1.getSelectedRow();
        System.out.println("Table row selected: " + s);
        if (s>=0){
             parent.newSong = availableSongsList.get(jTable1.convertRowIndexToModel(s));
            System.out.println("Selected song: " + parent.newSong);
        }
        submit(true); //submit and return to previus form
    }//GEN-LAST:event_saveJBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SelectSongJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SelectSongJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SelectSongJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SelectSongJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SelectSongJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Song> availableSongsList;
    private javax.persistence.Query availableSongsQuery;
    private javax.swing.JButton cancelJBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton saveJBtn;
    private javax.swing.JTextField searchInput;
    private javax.swing.JButton searchJBtn;
    private controller.TimeRenderer timeRenderer1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    JFrame thisFrame;
    EditListJFrame parent;
    
    //pat3group: notify listener
    private void submit(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false); //Hide Form
    }
}
